<!--
 * @Author: weikang
 * @Description:
 * @Date: 2023-12-23 11:41:29
 * @LastEditTime: 2025-01-26 17:23:31
 * @FilePath: /env-manager-pc/src/views/data_query/ent_day_power/index.vue
-->
<script setup lang="ts">
import dayjs from 'dayjs'
import dataQueryApi from '@/api/modules/data.query'
import { usePage } from '@/utils/commonHook'
import { useEnvOrgs, useOwnerOrgs } from '@/utils/dataHook'
import { QueryObj } from '@/utils/dataHook/data'
import useKeepAliveStore from '@/store/modules/keepAlive'
import useUserStore from '@/store/modules/user'

defineOptions({
  name: 'DataEntDayPowerList',
})
const keepAliveStore = useKeepAliveStore()

onBeforeRouteLeave((to) => {
  if (to.name === 'data-ent-day-power-detail') {
    keepAliveStore.add('DataEntDayPowerList')
  }
  else {
    keepAliveStore.remove('DataEntDayPowerList')
  }
})

const router = useRouter()
const userStore = useUserStore()
const tableData = ref<any[]>([])
const { page, pageNumChange, pageSizeChange } = usePage(getTableData)

const searchData = reactive(new QueryObj({
  objType: 'DIM.FilterCollection',
  Filters: ['DIM.Business.Envs.EnterpriseFilters.EnvOrgGUIDFilter', 'DIM.Units.Filters.NameFilter', 'DIM.Units.Filters.OwnerOrgGUIDFilter'],
}))

function search() {
  page.PageNum = 1
  getTableData()
}
const searchTime = ref([dayjs().subtract(7, 'day').format('YYYYMMDD'), dayjs().format('YYYYMMDD')])
const endTime = computed(() => {
  return dayjs(searchTime.value[1] || '').add(1, 'day').format('YYYYMMDD')
})
const timeClounm = ref<any>([])
const loading = ref(false)
async function getTableData() {
  loading.value = true
  const res = await dataQueryApi.GetEnterpriseElecEveryday({
    objFilter: searchData.getQuery(),
    pageSize: page.PageSize,
    pageNum: page.PageNum,
    startTime: searchTime.value[0],
    endTime: endTime.value,
  })
  loading.value = false
  const { Rows, RecordsetCount, Dates } = res as any
  timeClounm.value = Dates
  tableData.value = Rows || []
  page.RecordsetCount = RecordsetCount
}

getTableData()

function toDetail(row: any) {
  sessionStorage.setItem('ent_power', JSON.stringify(row))
  router.push(`/data-query/ent-day-power/${row.EntObjID}?startTime=${timeClounm.value[0]}&endTime=${timeClounm.value[timeClounm.value.length - 1]}`)
}

const OwnerList = userStore.isEnterpris ? [] : useOwnerOrgs()
const envOrgs = userStore.isEnterpris ? [] : useEnvOrgs()
const defaultProps = {
  children: 'Children',
  label: 'Name',
}

const column = computed(() => {
  const pushColunm = timeClounm.value.map((item: any, index: number) => {
    return {
      field: `Electricitys.${index}`, title: `${item}日电量(kWh)`, width: 200, slots: { default: ({ row }: any) => {
        return row.Electricitys[index]
      } },
    }
  })
  return [
    { type: 'seq', title: '序号', width: 90 },
    { field: 'EnvOrgName', title: '管理机构', minWidth: 120 },
    { field: 'OwnerOrgName', title: '运维公司', minWidth: 120 },
    { field: 'EntName', title: '企业名称', minWidth: 180, showOverflow: true },
    { title: '曲线数据', minWidth: 120, slots: { default: 'name_default' } },
    ...pushColunm,
  ]
})

const gridOptions: any = computed(() => {
  return {
    border: true,
    height: '100%',
    autoResize: true,
    loading: loading.value,
    columnConfig: {
      resizable: true,
    },
    columns: column.value,
    data: tableData.value,
    rowConfig: {
      isCurrent: true,
    },

  }
})

const minDate = ref()
const maxDate = ref()

function disabledDate(date: any) {
  if (!minDate.value) {
    return false
  }
  if (!maxDate.value) {
    return dayjs(minDate.value).add(29, 'day').isBefore(date) || dayjs(minDate.value).subtract(29, 'day').isAfter(date)
  }
  return false
}

function timeChange(val: any) {
  minDate.value = val[0]
  maxDate.value = val[1]
}
</script>

<template>
  <div>
    <PageHeader>
      <template #content>
        <ElForm label-width="100">
          <ElRow>
            <ElCol v-if="!userStore.isEnterpris" :span="6">
              <ElFormItem label="管理机构">
                <el-tree-select
                  v-model="searchData['DIM.Business.Envs.EnterpriseFilters.EnvOrgGUIDFilter']"
                  value-key="Code"
                  :data="envOrgs"
                  check-strictly
                  :render-after-expand="false"
                  :props="defaultProps"
                  clearable
                  class="w-full"
                />
              </ElFormItem>
            </ElCol>
            <ElCol :span="6">
              <ElFormItem label="企业名称">
                <ElInput v-model="searchData['DIM.Units.Filters.NameFilter']" clearable placeholder="请输入" />
              </ElFormItem>
            </ElCol>
            <ElCol v-if="!userStore.isEnterpris" :span="6">
              <ElFormItem label="运维公司">
                <el-tree-select
                  v-model="searchData['DIM.Units.Filters.OwnerOrgGUIDFilter']"
                  value-key="Code"
                  :data="OwnerList"
                  check-strictly
                  :render-after-expand="false"
                  :props="defaultProps"
                  clearable
                  class="w-full"
                />
              </ElFormItem>
            </ElCol>
            <ElCol :span="6">
              <ElFormItem label="日期">
                <ElDatePicker v-model="searchTime" type="daterange" value-format="YYYYMMDD" placeholder="选择日期" :clearable="false" :disabled-date="disabledDate" @calendar-change="timeChange" />
              </ElFormItem>
            </ElCol>
            <ElCol :span="6" :push="userStore.isEnterpris ? 6 : 18" class="flex flex-justify-end">
              <ElButton type="primary" @click="search">
                查询
              </ElButton>
            </ElCol>
          </ElRow>
        </ElForm>
      </template>
    </PageHeader>
    <PageMain>
      <div v-auto-height="85">
        <vxe-grid v-bind="gridOptions">
          <template #name_default="{ row }">
            <ElButton type="primary" link @click="toDetail(row)">
              曲线数据
            </ElButton>
          </template>
        </vxe-grid>
      </div>
      <ElPagination
        class="mt-4"
        :page-size="page.PageSize"
        :total="page.RecordsetCount"
        :current-page="page.PageNum"
        layout="total, sizes, prev, pager, next, jumper"
        :page-sizes="[20, 50, 100]"
        @current-change="pageNumChange"
        @size-change="pageSizeChange"
      />
    </PageMain>
  </div>
</template>
